package com.situ.blog.controller;

import com.situ.blog.util.JSONResult;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
@RequestMapping("/upload")
public class UploadController {

    // MultipartFile:封装了前台传递过来的图片的信息
    @RequestMapping("/uploadImage")
    @ResponseBody
    public JSONResult uploadImage(MultipartFile file) {
        System.out.println("UploadController.uploadImage");
        String uuid = UUID.randomUUID().toString().replace("-", "");
        //1162a8493f574204b7c6d8991ae8e573
        String filename = file.getOriginalFilename();
        System.out.println("filename: " + filename);//a.png
        String extension = FilenameUtils.getExtension(filename);//png
        String newFilename = uuid + "." + extension;//1162a8493f574204b7c6d8991ae8e573.png
        System.out.println("newFilename: " + newFilename);

        //把图片放到D:/mypic下面
        String filePath = "D:\\mypic\\" + newFilename;
        try {
            file.transferTo(new File(filePath));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return JSONResult.ok("上传成功", newFilename);
    }

    public static void main(String[] args) {
        String uuid = UUID.randomUUID().toString();
        System.out.println(uuid);//6d2949aa-1089-4677-b74d-f37600dfd8b4
        //1162a8493f574204b7c6d8991ae8e573
        System.out.println(uuid.replace("-", ""));
    }
}
